import {
  getAddressList,
  saveAddress,
  getUpdateAddressInfo,
  updateAddress,
  removeAddress
} from '../../request/api'
import { areaList } from '../../node_file/area-data/dist/data'
import Toast from '@vant/weapp/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressList: [],
    areaList: areaList,
    showSaveAddressPopup: false,
    saveLoading: false,
    saveAddressForm: {
      address: '',
      addressDetail: '',
      phone: null
    },
    selectAddressShow: false
    // areaList: []
    // cascaderAreaData: areaList()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },
  phoneChange(e) {
    this.setData({
      ['saveAddressForm.phone']: Number(e.detail)
    })
  },
  addressDetailChange(e) {
    this.setData({
      ['saveAddressForm.addressDetail']: e.detail
    })
  },
  confirmArea(e) {
    const arr = []
    e.detail.values.forEach(v => {
      arr.push(v.name)
    })
    this.setData({
      ['saveAddressForm.address']: arr.join(''),
      selectAddressShow: false
    })
  },
  showSaveAddress() {
    this.setData({
      showSaveAddressPopup: true,
      options: areaList
    })
  },
  hideSaveAddress() {
    this.setData({
      showSaveAddressPopup: false
    })
  },
  saveAddressHandler() {
    console.log(this.data.saveAddressForm)
    let phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/
    if (!phoneReg.test(this.data.saveAddressForm.phone)) {
      Toast({
        type: 'fail',
        message: '手机号不正确',
        duration: 3000
      })
      return
    } else if (this.data.saveAddressForm.phone == null) {
      Toast({
        type: 'fail',
        message: '手机号不能未空',
        duration: 3000
      })
      return
    } else if (this.data.saveAddressForm.address == '') {
      Toast({
        type: 'fail',
        message: '地区不能为空',
        duration: 3000
      })
      return
    } else if (this.data.saveAddressForm.addressDetail == '') {
      Toast({
        type: 'fail',
        message: '详细地址不能为空',
        duration: 3000
      })
      return
    } else {
      this.setData({
        saveLoading: true
      })
      saveAddress(this.data.saveAddressForm).then(res => {
        if (res.code == 200) {
          Toast({
            type: 'success',
            message: '添加成功',
            duration: 3000
          })
          console.log('添加地址', res)
          this.setData({
            saveLoading: false,
            showSaveAddressPopup: false
          })
        } else {
          Toast({
            type: 'fail',
            message: '添加失败',
            duration: 3000
          })
          this.setData({
            saveLoading: false
          })
        }
      })
    }
  },
  onClick() {
    this.setData({
      selectAddressShow: true,
    });
  },

  hideSelectAddress() {
    this.setData({
      selectAddressShow: false,
    });
  },
})